//Erstellt von Moritz Liepe
package main.simulation;

import main.IModuleControl;
import main.Module;

import org.eclipse.draw2d.Figure;
import org.eclipse.swt.widgets.Display;


public class FullAdderBehavior implements IBehavior
{

	@Override
	public void simulate(Module module) 
	{
		boolean carryin = false;
		boolean ina = false;
		boolean inb = false;
		boolean carryout = false;
		boolean out = false;
		
		IModuleControl carryInControl = null;
		IModuleControl inAControl = null;
		IModuleControl inBControl = null;
		IModuleControl carryOutControl = null;
		IModuleControl outControl = null;
		
		for(int i = 0; i < module.getChildren().size(); i++)
		{
			Figure moduleChild  = (Figure)module.getChildren().get(i);
			if(moduleChild instanceof IModuleControl)
			{
				IModuleControl control = (IModuleControl)moduleChild ;
				if(control.getAddress().equals("carryin"))
				{
					carryInControl = control;
					continue;
				}
				if(control.getAddress().equals("ina"))
				{
					inAControl = control;
					continue;
				}
				if(control.getAddress().equals("inb"))
				{
					inBControl = control;
					continue;
				}
				if(control.getAddress().equals("carryout"))
				{
					carryOutControl = control;
					continue;
				}
				if(control.getAddress().equals("sum"))
				{
					outControl = control;
					continue;
				}
			}
		}
		
		//Parse
		
		if((carryInControl.getValue() != null) && carryInControl.getValue().equals(Boolean.toString(true)))
		{
			carryin = true;
		}
		if((inAControl.getValue() != null) &&  inAControl.getValue().equals(Boolean.toString(true)))
		{
			ina = true;
		}
		if((inBControl.getValue() != null) &&  inBControl.getValue().equals(Boolean.toString(true)))
		{
			inb = true;
		}
		
		int number = carryin ? 1 : 0;
		number 		+= ina ? 1 : 0;
		number 		+= inb ? 1 : 0;
		
		//Calculate Carry
		
		if(number > 1)
		{
			carryout = true;
		}
		
		if((carryOutControl.getValue() == null) || (! carryOutControl.getValue().equals(Boolean.toString(carryout))))
		{
			Display.getDefault().asyncExec(new SetControlValue(carryOutControl,Boolean.toString(carryout)));
		}
		
		//Calculate Sum
		
		if((number == 1) || (number == 3))
		{
			out = true;
		}
		
		if((outControl.getValue() == null) || (! outControl.getValue().equals(Boolean.toString(out))))
		{
			Display.getDefault().asyncExec(new SetControlValue(outControl,Boolean.toString(out)));
		}
	}

}
